package com.bawei.module_mall

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.module_mall.databinding.ActivityAddressBinding
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.module_mall.http.viewModel.ShopViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.model.AddressModelItem
import android.app.Activity

class AddressAdapter(
    private var data: List<AddressModelItem>,
    private val onAddressSelected: (AddressModelItem) -> Unit,
    private val onEdit: (AddressModelItem) -> Unit,
    private val onDelete: (AddressModelItem) -> Unit
) : RecyclerView.Adapter<AddressAdapter.ViewHolder>() {
    inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        val tvName = view.findViewById<TextView>(R.id.tv_name)
        val tvPhone = view.findViewById<TextView>(R.id.tv_phone)
        val tvAddress = view.findViewById<TextView>(R.id.tv_address)
        val tvDefault = view.findViewById<TextView>(R.id.tv_mo_ren)
        val cbSelect = view.findViewById<CheckBox>(R.id.cb_mo_ren)
        val ivEdit = view.findViewById<ImageView>(R.id.img_update)
        val ivDelete = view.findViewById<ImageView>(R.id.img_delete)
    }
    private var selectedPosition = -1

    // 计算最后一个 isDefault==1 的下标
    private fun getLastDefaultPosition(): Int {
        for (i in data.indices.reversed()) {
            if (data[i].isDefault == 1) return i
        }
        return -1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = android.view.LayoutInflater.from(parent.context).inflate(R.layout.item_address, parent, false)
        return ViewHolder(v)
    }
    override fun getItemCount() = data.size
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = data[position]
        holder.tvName.text = item.receiverName
        holder.tvPhone.text = item.receiverPhone
        holder.tvAddress.text = "${item.provinceName}${item.cityName}${item.districtName}${item.address}"

        // 只显示最后一个 isDefault==1 的"默认"标记
        val defaultPos = getLastDefaultPosition()
        holder.tvDefault.visibility = if (position == defaultPos) View.VISIBLE else View.GONE

        // CheckBox选中状态
        holder.cbSelect.isChecked = position == selectedPosition
        holder.cbSelect.setOnClickListener {
            selectedPosition = holder.adapterPosition
            notifyDataSetChanged()
            onAddressSelected(item)
            // 选中后立即回传数据并关闭页面
            val intent = Intent()
            intent.putExtra("addressName", item.receiverName)
            intent.putExtra("addressPhone", item.receiverPhone)
            intent.putExtra("addressDetail", "${item.provinceName}${item.cityName}${item.districtName}${item.address}")
            (holder.itemView.context as? Activity)?.setResult(Activity.RESULT_OK, intent)
            (holder.itemView.context as? Activity)?.finish()
        }
        holder.ivEdit.setOnClickListener {
            onEdit(item)
        }
        holder.ivDelete.setOnClickListener {
            Log.d("AddressAdapter", "删除按钮被点击，地址ID: ${item.id}")
            onDelete(item)
        }
    }
    fun update(newData: List<AddressModelItem>) {
        data = newData
        notifyDataSetChanged()
    }
    
    fun getCurrentData(): List<AddressModelItem> {
        return data
    }
}

@Route(path = Router.Ui.ADDRESS_ACTIVITY)
class AddressActivity : BaseActivity() {

    private val binding by lazy {
        ActivityAddressBinding.inflate(layoutInflater)
    }
    private lateinit var viewModel: ShopViewModel
    private lateinit var adapter: AddressAdapter
    private var addressList: List<AddressModelItem> = emptyList()
    private var selectedAddress: AddressModelItem? = null

    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[ShopViewModel::class.java]
        viewModel.handleIntent()
        initRecyclerView()
        
        // 右上角加号点击（跳转添加地址页）
        binding.imgAdd.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.ADDADDRESS_ACTIVITY).navigation(this, 1001)
        }

        binding.imgBtn.setOnClickListener {
            finish()
        }
        binding.btnAddAddress.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.ADDADDRESS_ACTIVITY).navigation(this, 1001)
        }

        // 监听 ViewModel 状态，动态切换布局
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    Log.d("AddressActivity", "收到状态: $state")
                    when (state) {
                        is ShopState.Loading -> {
                            // 显示加载中（可加 ProgressBar，你的布局里没有就跳过）
                            Log.d("AddressActivity", "加载中...")
                        }
                        is ShopState.GetAddressSuccess -> {
                            val addressModel = state.data
                            Log.d("AddressActivity", "获取地址成功，数量: ${addressModel?.size}")
                            // 👇 逻辑反转：isEmpty() 为 true 表示"无数据"，应显示空布局
                            if (addressModel?.isNotEmpty() == true) {
                                // 有地址：显示 RecyclerView，隐藏空布局
                                binding.recyclerView.visibility = View.VISIBLE
                                binding.ivEmpty.visibility = View.GONE
                                binding.tvEmptyTip.visibility = View.GONE
                                binding.btnAddAddress.visibility = View.GONE
                                showAddressList(addressModel)
                            } else {
                                // 无地址：显示空布局，隐藏 RecyclerView
                                binding.recyclerView.visibility = View.GONE
                                binding.ivEmpty.visibility = View.VISIBLE
                                binding.tvEmptyTip.visibility = View.VISIBLE
                                binding.btnAddAddress.visibility = View.VISIBLE
                            }
                        }
                        is ShopState.AddAddressSuccess -> {
                            Log.d("AddressActivity", "添加地址成功，准备刷新列表")
                            Toast.makeText(this@AddressActivity, "添加成功", Toast.LENGTH_SHORT).show()
                            // 添加成功后自动刷新
                            requestAddressList()
                        }
                        is ShopState.UpdateAddressSuccess -> {
                            Log.d("AddressActivity", "更新地址成功，准备刷新列表")
                            Toast.makeText(this@AddressActivity, "更新成功", Toast.LENGTH_SHORT).show()
                            // 更新成功后自动刷新
                            requestAddressList()
                        }
                        is ShopState.DeleteAddressSuccess -> {
                            Log.d("AddressActivity", "删除地址成功，准备刷新列表")
                            Toast.makeText(this@AddressActivity, "删除成功", Toast.LENGTH_SHORT).show()
                            // 删除成功后自动刷新
                            requestAddressList()
                        }
                        is ShopState.Error -> {
                            Log.e("AddressActivity", "错误: ${state.error}")
                            Toast.makeText(this@AddressActivity, state.error, Toast.LENGTH_SHORT).show()
                            // 如果是删除操作失败，重新获取列表以恢复状态
                            if (state.error.contains("删除") || state.error.contains("delete")) {
                                requestAddressList()
                            } else {
                                // 加载失败也显示空布局（可选）
                                binding.recyclerView.visibility = View.GONE
                                binding.ivEmpty.visibility = View.VISIBLE
                                binding.tvEmptyTip.visibility = View.VISIBLE
                                binding.btnAddAddress.visibility = View.VISIBLE
                            }
                        }
                        else -> {
                            Log.d("AddressActivity", "其他状态: $state")
                        }
                    }
                }
            }
        }

        // 最后请求地址列表
        requestAddressList()
    }

    private fun initRecyclerView() {
        adapter = AddressAdapter(addressList,
            onAddressSelected = { address ->
                selectedAddress = address
                Toast.makeText(this, "已选择该地址为发货地址", Toast.LENGTH_SHORT).show()
            },
            onEdit = { address ->
                // 跳转编辑页面，传递address.id或完整对象
                ARouter.getInstance().build(Router.Ui.ADDADDRESS_ACTIVITY)
                    .withSerializable("address", address) // AddressModelItem 需实现 Serializable
                    .navigation(this, 1002)
            },
            onDelete = { address ->
                Log.d("AddressActivity", "准备删除地址: ${address.id}")
                // 弹窗确认删除
                android.app.AlertDialog.Builder(this)
                    .setTitle("删除地址")
                    .setMessage("确定要删除该地址吗？")
                    .setPositiveButton("删除") { _, _ ->
                        Log.d("AddressActivity", "用户确认删除，发送删除请求")
                        // 立即从本地列表中移除该地址，实现即时更新
                        val currentList = adapter.getCurrentData().toMutableList()
                        currentList.removeAll { it.id == address.id }
                        adapter.update(currentList)
                        
                        // 如果列表为空，显示空状态
                        if (currentList.isEmpty()) {
                            binding.recyclerView.visibility = View.GONE
                            binding.ivEmpty.visibility = View.VISIBLE
                            binding.tvEmptyTip.visibility = View.VISIBLE
                            binding.btnAddAddress.visibility = View.VISIBLE
                        }
                        
                        // 发送删除请求到服务器
                        lifecycleScope.launch {
                            viewModel.intents.send(ShopIntent.DeleteAddress(address.id))
                        }
                    }
                    .setNegativeButton("取消", null)
                    .show()
            }
        )
        val layoutManager = LinearLayoutManager(this).apply {
            reverseLayout = true
            stackFromEnd = true
        }
        binding.recyclerView.layoutManager = layoutManager
        binding.recyclerView.adapter = adapter
    }

    private fun requestAddressList() {
        lifecycleScope.launch {
            // 确保发送 GetAddress 意图
            viewModel.intents.send(ShopIntent.GetAddress)
        }
    }
    // 无适配器，动态添加列表项
    private fun showAddressList(addressList: List<AddressModelItem>) {
        adapter.update(addressList)
    }

    // dp 转 px 工具函数
    private fun Int.dpToPx(): Int = (this * resources.displayMetrics.density).toInt()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if ((requestCode == 1001 || requestCode == 1002) && resultCode == RESULT_OK) {
            requestAddressList()
        }
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }
}